<script setup lang="ts">
import type { CustomDialogInstance, SaveOrUpdateCarbonInventoryActivityBodyType } from '@/types'
import type { PanchaInformation } from '../pancha-information/type'
import type { FormInstance, FormRules } from 'element-plus'
import { TANPANCHA_DATA_FILL_TYPE, TANPANCHA_DATA_SOURCE_TYPE, TANPANCHA_TYPE } from '@/constant/modules/tanpancha'
import EmissionFactors from './emission-factors.vue'

import { carbonInventoryApi } from '@/api'

import EmissionSourceSelect from './emission-source-select.vue'
import RealNumberInput from '@/components/RealNumberInput/index.vue'

type Activity = Omit<PanchaInformation['dataList'][number]['categoryList'][number]['facilityActivityList'][number], 'gasList'>
interface GasItem {
  [key: string]: any
  gas: string
  emissionFactor: number | string
  emissionUnitFactor: string
  emissionUnit: string
  unit: string
  gwp: number
  discountValue: number
}

defineOptions({ name: 'PanchaActivity' })

const props = defineProps<{
  pointId: number
  pointName: string
  dataTime: string | number
  protocolCode: string
  categoryName: string
  subCategoryName: string
  categoryId: number
  activityId?: number
  convertFacilityListToTableList: (list: any[]) => any[]
}>()

const emit = defineEmits<{
  (e: 'open'): void
  (e: 'close'): void
  (e: 'saveSuccess', data: {
    carbonInventoryId: number
    id: number
    [key: string]: any
    categoryId: number
  }): void
}>()

const emissionFactorRef = ref<InstanceType<typeof EmissionFactors>>()

const tanpanchaStore = useTanpanchaStore()
const dialogRef = ref<CustomDialogInstance>()
const formRef = ref<FormInstance>()
const info = ref({
  emissionSource: '',
  emissionType: TANPANCHA_TYPE.EMISSION,
  sourceType: TANPANCHA_DATA_SOURCE_TYPE.MANUAL,
} as unknown as Activity)
const rules: FormRules = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur',
    },
  ],
  emissionSource: [
    {
      required: true,
      message: '请输入排放源',
      trigger: 'change',
    },
  ],
  emissionType: [
    {
      required: true,
      message: '请选择排放类型',
      trigger: 'change',
    },
  ],
  sourceType: [
    {
      required: true,
      message: '请选择数据来源',
      trigger: 'change',
    },
  ],
  entryMethod: [
    {
      required: true,
      message: '请选择数据填报方式',
      trigger: 'change',
    },
  ],
  unit: [
    {
      required: true,
      message: '请输入数据单位',
      trigger: 'blur',
    },
  ],
  indicatorNumber: [
    {
      required: true,
      message: '请输入指标编码',
      trigger: 'blur',
    },
  ],
}
const list = ref<GasItem[]>([])
const filterGasOptions = ref<{ label: string, value: string, [key: string]: any }[]>([])

function hasEmptyInList(list: GasItem[]) {
  return list.some((item) => {
    return !item.gas || !item.emissionFactor || !item.emissionUnitFactor || !item.emissionUnit || !item.gwp || !item.discountValue
  })
}
async function clickSave(done: () => void) {
  const isValid = await formRef.value?.validate().catch(() => {
    done()
  })
  if (!isValid) {
    done()
    return false
  }
  if (list.value.length === 0) {
    ElMessage.warning('请至少填写一项影响因子配置')
    done()
    return false
  }
  if (hasEmptyInList(list.value)) {
    ElMessage.warning('请填写完整影响因子配置')
    done()
    return false
  }
  const params = {
    ...unref(info),
    pointId: props.pointId,
    protocolCode: props.protocolCode,
    dataTime: props.dataTime,
    categoryId: props.categoryId,
    gasList: list.value.map(v => ({
      gas: v.gas,
      emissionFactor: v.emissionFactor,
      emissionUnitFactor: v.emissionUnitFactor,
      emissionUnit: v.emissionUnit,
      gwp: v.gwp,
      discountValue: v.discountValue,
    })),
  } as unknown as SaveOrUpdateCarbonInventoryActivityBodyType

  // 数据来源为设备采集时，填报方式传月
  if (params.sourceType === TANPANCHA_DATA_SOURCE_TYPE.AUTOMITIC) {
    params.entryMethod = TANPANCHA_DATA_FILL_TYPE.MONTH
  }
  try {
    const { data } = await carbonInventoryApi.saveOrUpdateCarbonInventoryActivity(params)
    done()
    close()
    emit('saveSuccess', { ...data, categoryId: props.categoryId })
  }
  catch (e) {
    done()
  }
}
async function handleAdd() {
  const item = {
    gas: '',
    emissionFactor: '',
    emissionUnitFactor: '',
    emissionUnit: '',
    unit: info.value.unit,
    gwp: undefined,
    discountValue: undefined,
  } as unknown as GasItem
  list.value.push(item)
}

function handleIndicatorChange(indicatorNumber: string) {
  const target = tanpanchaStore.indicatorOptions.find(v => v.value === indicatorNumber)
  console.log(indicatorNumber, target)
  if (target) {
    info.value.unit = target.unit
  }
}

function handleGasVisibleChange(cur: string, show: boolean) {
  if (show) {
    const has = (gas: string) => list.value.some(v => v.gas === gas)
    for (const item of filterGasOptions.value) {
      item.disabled = has(item.value)
    }
  }
}

function handleChangeGas(row: GasItem) {
  const target = tanpanchaStore.gasOptions.find(v => v.gas === row.gas)
  if (target) {
    row.gwp = target.gwp
    row.emissionUnit = `kg${target.gas}`
  }
}

function handleRemoveGasItem(row: GasItem) {
  const index = list.value.indexOf(row)
  if (index > -1) {
    list.value.splice(index, 1)
  }
}

function handleSelectFromEmissionFactors(row: GasItem) {
  emissionFactorRef.value?.open()
}

async function handleSelectEmissionFactor(item: any) {
  // 只有CO2才从可能因子库中获取
  const target = list.value.find(v => v.gas === 'CO2')
  if (target) {
    target.emissionFactor = item.emissionFactors
    target.emissionUnitFactor = item.unit
  }
}

async function getActivityDetails() {
  // 新增时清空数据
  if (!props.activityId) {
    info.value = {
      emissionType: TANPANCHA_TYPE.EMISSION,
      sourceType: TANPANCHA_DATA_SOURCE_TYPE.MANUAL,
    } as unknown as Activity
    list.value = []
    return
  }
  try {
    const { data } = await carbonInventoryApi.queryCarbonInventoryActivityDetailsById(props.activityId!)
    const { gasList, ...other } = data
    info.value = { ...other }
    list.value = props.convertFacilityListToTableList([data])
  }
  catch (error) {
    console.error(error)
  }
}

function handleInputBlur(row: GasItem, key: keyof GasItem, value: number | null) {
  console.log('blur: ', value)
  row[key] = value
}

async function open() {
  tanpanchaStore.getEmissionSourceOptions()
  if (props.pointId) {
    tanpanchaStore.getIndicatorOptions(props.pointId)
  }
  getActivityDetails()
  await tanpanchaStore.getGasOptions()
  filterGasOptions.value = (tanpanchaStore.gasOptions).map(v => ({
    ...v,
    disabled: false,
  }))
  await nextTick()
  dialogRef.value?.open()
  emit('open')
}
async function close() {
  dialogRef.value?.close()
  emit('close')
}

watch(() => info.value.unit, (val) => {
  list.value = list.value.map(v => ({
    ...v,
    unit: val,
  }))
})

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog ref="dialogRef" title="设施/活动配置" width="1040px" need-saving no-max-height @confirm="clickSave">
    <div class="py-3 opacity-80">
      基本信息
    </div>
    <ElRow class="py-1">
      <ElCol :span="8">
        <div class="flex items-center">
          <span>核算时间：</span>
          <span>{{ dataTime }}</span>
        </div>
      </ElCol>
      <ElCol :span="8">
        <div class="flex items-center">
          <span>核算标准：</span>
          <span>{{ protocolCode }}</span>
        </div>
      </ElCol>
      <ElCol :span="8">
        <div class="flex items-center">
          <span>核算主体：</span>
          <span>{{ pointName }}</span>
        </div>
      </ElCol>
    </ElRow>
    <ElRow class="py-1">
      <ElCol :span="24">
        <div class="flex items-center">
          <span>核算类别：</span>
          <span>{{ categoryName }} > {{ subCategoryName }}</span>
        </div>
      </ElCol>
    </ElRow>
    <div class="py-3 opacity-80">
      排放源配置
    </div>
    <ElForm ref="formRef" :model="info" :rules="rules" label-width="120px">
      <ElRow>
        <ElCol :span="8">
          <ElFormItem class="!mb-0" label="设施/活动名称" prop="name">
            <ElInput v-model="info.name" :maxlength="60" placeholder="请输入设施/活动名称" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem class="!mb-0" label="排放源" prop="emissionSource">
            <EmissionSourceSelect v-model="info.emissionSource" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem class="!mb-0" label="排放类型" prop="emissionType">
            <ElSelect v-model="info.emissionType">
              <ElOption v-for="item in tanpanchaStore.emissionTypeOptions" :key="item.value" v-bind="item" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
      </ElRow>
      <div class="py-3 opacity-80">
        活动数据配置
      </div>
      <ElRow>
        <ElCol :span="8">
          <ElFormItem class="!mb-0" label="数据采集方式" prop="sourceType">
            <ElSelect v-model="info.sourceType">
              <ElOption v-for="item in tanpanchaStore.sourceTypeOptions" :key="item.value" v-bind="item" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem
            v-if="info.sourceType === TANPANCHA_DATA_SOURCE_TYPE.MANUAL" class="!mb-0" label="数据填报方式"
            prop="entryMethod"
          >
            <ElSelect v-model="info.entryMethod">
              <ElOption v-for="item in tanpanchaStore.fillTypeOptions" :key="item.value" v-bind="item" />
            </ElSelect>
          </ElFormItem>
          <ElFormItem v-else label="数据采集指标" prop="indicatorNumber">
            <ElSelect v-model="info.indicatorNumber" @change="handleIndicatorChange">
              <ElOption v-for="item in tanpanchaStore.indicatorOptions" :key="item.value" v-bind="item">
                <span style="float: left">{{ item.label }}</span>
                <span
                  style="
                    float: right;
                    color: var(--el-text-color-secondary);
                    font-size: 13px;
                  "
                >
                  {{ item.value }}
                </span>
              </ElOption>
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem class="!mb-0" label="单位" prop="unit">
            <ElInput v-model="info.unit" placeholder="请输入单位" :disabled="info.sourceType !== TANPANCHA_DATA_SOURCE_TYPE.MANUAL" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="24">
          <ElFormItem label="数据说明" class="mt-4" label-class="font-600">
            <ElInput
              v-model="info.dataExplain" :maxlength="100" show-word-limit type="textarea"
              class="el-input__wrapper !px-0"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
    <div class="py-3 opacity-80">
      影响因子配置
    </div>
    <ElTable :data="list" size="small">
      <ElTableColumn prop="gas" label="气体类型">
        <template #default="{ row }">
          <ElSelect
            v-model="row.gas" placeholder="请选择气体类型" @visible-change="handleGasVisibleChange(row.gas, $event)"
            @change="handleChangeGas(row)"
          >
            <ElOption
              v-for="item in filterGasOptions" :key="item.value" :label="item.label" :value="item.value"
              :disabled="item.disabled"
            />
          </ElSelect>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="emissionFactor" label="排放因子值">
        <template #default="{ row }">
          <RealNumberInput
            :initial-value="row.emissionFactor"
            @blur="handleInputBlur(row, 'emissionFactor', $event)"
          />
        </template>
      </ElTableColumn>
      <ElTableColumn prop="emissionUnitFactor" label="因子单位">
        <template #default="{ row }">
          <ElInput v-model.trim="row.emissionUnitFactor" placeholder="请输入因子单位" />
        </template>
      </ElTableColumn>
      <ElTableColumn prop="emissionUnit" label="排放单位" />
      <ElTableColumn prop="unit" label="活动数据单位" />
      <ElTableColumn prop="gwp" label="GWP">
        <template #default="{ row }">
          <RealNumberInput
            :initial-value="row.gwp"
            @blur="handleInputBlur(row, 'gwp', $event)"
          />
        </template>
      </ElTableColumn>
      <ElTableColumn prop="discountValue" label="换算比例">
        <template #default="{ row }">
          <RealNumberInput
            :initial-value="row.discountValue"
            @blur="handleInputBlur(row, 'discountValue', $event)"
          />
        </template>
      </ElTableColumn>
      <ElTableColumn prop="discountValue" label="操作">
        <template #default="{ row }">
          <ElLink
            v-if="row.gas === 'CO2'" :underline="false" type="warning" class="mr-3"
            @click="handleSelectFromEmissionFactors(row)"
          >
            从因子库选择
          </ElLink>
          <ElLink :underline="false" type="danger" @click="handleRemoveGasItem(row)">
            删除
          </ElLink>
        </template>
      </ElTableColumn>
    </ElTable>
    <div class="p-3">
      <ElLink
        v-if="list.length < tanpanchaStore.gasOptions.length" type="warning" plain size="small"
        @click="handleAdd"
      >
        +新增气体
      </ElLink>
    </div>
    <div class="py-3 opacity-80">
      影响因子说明
    </div>
    <ElInput
      v-model="info.gasExplain" :maxlength="100" show-word-limit type="textarea"
      class="el-input__wrapper !px-0"
    />

    <EmissionFactors ref="emissionFactorRef" @select-emission-factor="handleSelectEmissionFactor" />
  </CustomDialog>
</template>
